# import pygame
# import random
# import os
# import math
#
# # 初始化Pygame
# pygame.init()
#
# # 游戏窗口设置
# SCREEN_WIDTH = 480
# SCREEN_HEIGHT = 720
# screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
# pygame.display.set_caption("羊了个羊")
#
# # 颜色定义
# BG_COLOR = (255, 255, 255)
# TEXT_COLOR = (0, 0, 0)
# CAPACITY_COLOR = (100, 100, 100)
# ITEM_COLOR_1 = (0, 128, 0)  # 撤销道具颜色
# ITEM_COLOR_2 = (0, 0, 128)  # 洗牌道具颜色
# ITEM_TEXT_COLOR = (255, 255, 255)
# WIN_COLOR = (0, 128, 0)    # 胜利文字颜色
# LOSE_COLOR = (255, 0, 0)    # 失败文字颜色
# BUTTON_COLOR = (65, 105, 225)  # 按钮背景色
# BUTTON_HOVER_COLOR = (70, 130, 180)  # 按钮悬停色
# BUTTON_TEXT_COLOR = (255, 255, 255)  # 按钮文字颜色
#
# # 卡片尺寸和间距
# CARD_WIDTH = 50
# CARD_HEIGHT = 60
# SPACING = 10
# # 叠罗汉偏移量
# OVERLAP_OFFSET =4
#
# # 游戏区域布局
# GRID_ROWS = 6
# GRID_COLS = 6
# grid_width = GRID_COLS * (CARD_WIDTH + SPACING) - SPACING
# GRID_LEFT = (SCREEN_WIDTH - grid_width) // 2
# GRID_TOP = 100
#
# # 槽位区域设置
# SLOT_ROWS = 1
# SLOT_COLS = 7  # 最多存放7个卡片
# slot_width = SLOT_COLS * (CARD_WIDTH + 5) - 5
# SLOT_LEFT = (SCREEN_WIDTH - slot_width) // 2
# SLOT_TOP = SCREEN_HEIGHT - CARD_HEIGHT - 50
# SLOT_HEIGHT = CARD_HEIGHT + 20
#
# # 道具按钮设置
# ITEM_WIDTH = 60  # 道具按钮宽度
# ITEM_HEIGHT = 60  # 道具按钮高度
# ITEM_SPACING = 20  # 道具按钮间距
# ITEM_TOP = 20  # 道具按钮顶部位置
# ITEM_LEFT = (SCREEN_WIDTH - (2 * ITEM_WIDTH + ITEM_SPACING)) // 2  # 道具按钮左侧起始位置
#
# # 重玩按钮设置
# RESTART_BUTTON_WIDTH = 150
# RESTART_BUTTON_HEIGHT = 50
# RESTART_BUTTON_LEFT = (SCREEN_WIDTH - RESTART_BUTTON_WIDTH) // 2
# RESTART_BUTTON_TOP = SCREEN_HEIGHT // 2 + 50
#
# # 动画常量
# ANIMATION_DURATION = 30  # 消去动画持续时间
# MOVE_DURATION = 20  # 卡片移动动画持续时间
#
# # 加载背景图像
# try:
#     image_folder = os.path.join(os.path.dirname(__file__), "image")
#     background_path = os.path.join(image_folder, "back.png")
#     background_img = pygame.image.load(background_path)
#     background_img = pygame.transform.scale(background_img, (SCREEN_WIDTH * 2, SCREEN_HEIGHT))
#     print("主背景图像加载成功")
#     bg_x = 0
#     BG_MOVE_SPEED = 1
# except Exception as e:
#     print(f"主背景图像加载失败: {e}")
#     background_img = None
#     bg_x = 0
#
#
#
# # 加载槽位背景图像
# try:
#     slot_bg_path = os.path.join(image_folder, "back2.png")
#     slot_bg_img = pygame.image.load(slot_bg_path)
#     slot_bg_img = pygame.transform.scale(slot_bg_img, (slot_width + 20, SLOT_HEIGHT + 20))
#     print("槽位背景图像加载成功")
# except Exception as e:
#     print(f"槽位背景图像加载失败: {e}")
#     slot_bg_img = None
#
# # 加载卡片图片
# card_images = []
# try:
#     for i in range(7):
#         if i == 0:
#             tile_path = os.path.join(image_folder, "tile.png")
#         else:
#             tile_path = os.path.join(image_folder, f"tile{i}.png")
#
#         if os.path.exists(tile_path):
#             img = pygame.image.load(tile_path)
#             img = pygame.transform.scale(img, (CARD_WIDTH, CARD_HEIGHT))
#             card_images.append(img)
#             print(f"卡片图片 {os.path.basename(tile_path)} 加载成功")
#         else:
#             print(f"卡片图片 {tile_path} 不存在")
#
#     if not card_images:
#         raise Exception("没有找到任何卡片图片")
#
# except Exception as e:
#     print(f"卡片图片加载失败: {e}")
#     COLORS = [
#         (255, 0, 0),  # 红
#         (0, 255, 0),  # 绿
#         (0, 0, 255),  # 蓝
#         (255, 255, 0),  # 黄
#         (128, 0, 128),  # 紫
#         (255, 165, 0),  # 橙
#         (0, 191, 255),  # 天蓝
#     ]
#
# # 加载道具按钮图片
# try:
#     # 撤销道具图片 (tuixiao.PNG)
#     undo_img_path = os.path.join(image_folder, "chexiao.PNG")
#     undo_button_img = pygame.image.load(undo_img_path)
#     undo_button_img = pygame.transform.scale(undo_button_img, (ITEM_WIDTH, ITEM_HEIGHT))
#     undo_button_hover_img = pygame.transform.scale(undo_button_img, (ITEM_WIDTH + 5, ITEM_HEIGHT + 5))
#     print("撤销道具图片加载成功")
# except Exception as e:
#     print(f"撤销道具图片加载失败: {e}")
#     undo_button_img = None
#     undo_button_hover_img = None
#
# try:
#     # 洗牌道具图片 (xipai.PNG)
#     shuffle_img_path = os.path.join(image_folder, "xipai.PNG")
#     shuffle_button_img = pygame.image.load(shuffle_img_path)
#     shuffle_button_img = pygame.transform.scale(shuffle_button_img, (ITEM_WIDTH, ITEM_HEIGHT))
#     shuffle_button_hover_img = pygame.transform.scale(shuffle_button_img, (ITEM_WIDTH + 5, ITEM_HEIGHT + 5))
#     print("洗牌道具图片加载成功")
# except Exception as e:
#     print(f"洗牌道具图片加载失败: {e}")
#     shuffle_button_img = None
#     shuffle_button_hover_img = None
#
# # 加载重玩按钮图片
# try:
#     restart_img_path = os.path.join(image_folder, "chongwan.PNG")
#     restart_button_img = pygame.image.load(restart_img_path)
#     restart_button_img = pygame.transform.scale(restart_button_img, (RESTART_BUTTON_WIDTH, RESTART_BUTTON_HEIGHT))
#     restart_button_hover_img = pygame.transform.scale(restart_button_img, (RESTART_BUTTON_WIDTH + 5, RESTART_BUTTON_HEIGHT + 5))
#     print("重玩按钮图片加载成功")
# except Exception as e:
#     print(f"重玩按钮图片加载失败: {e}")
#     restart_button_img = None
#     restart_button_hover_img = None
#
# # 粒子效果类
# class Particle:
#     def __init__(self, x, y, color):
#         self.x = x
#         self.y = y
#         self.color = color
#         self.radius = random.randint(2, 5)
#         self.speed_x = random.uniform(-3, 3)
#         self.speed_y = random.uniform(-5, -1)
#         self.gravity = 0.1
#         self.life = random.randint(20, 40)
#
#     def update(self):
#         self.x += self.speed_x
#         self.y += self.speed_y
#         self.speed_y += self.gravity
#         self.life -= 1
#
#     def draw(self, surface):
#         alpha = int((self.life / 40) * 255)
#         if alpha > 0:
#             s = pygame.Surface((self.radius * 2, self.radius * 2), pygame.SRCALPHA)
#             pygame.draw.circle(s, (*self.color, alpha), (self.radius, self.radius), self.radius)
#             surface.blit(s, (int(self.x - self.radius), int(self.y - self.radius)))
#
#
# # 得分增加动画类
# class ScorePopup:
#     def __init__(self, x, y):
#         self.x = x
#         self.y = y
#         self.value = "+1"
#         self.font = pygame.font.SysFont(None, 30)  # 使用默认字体
#         self.color = (255, 215, 0)  # 金色
#         self.life = 40
#         self.speed_y = -1
#
#     def update(self):
#         self.y += self.speed_y
#         self.life -= 1
#
#     def draw(self, surface):
#         alpha = int((self.life / 40) * 255)
#         if alpha > 0:
#             text = self.font.render(self.value, True, self.color)
#             text.set_alpha(alpha)
#             surface.blit(text, (self.x, self.y))
#
#
# # 初始化游戏
# def init_game():
#     global slots, score, game_over, game_won, grid, undo_history, remove_card_count, shuffle_count, particles, score_popups, eliminate_animation, eliminate_indices, animation_timer, card_moving, moving_card, start_x, start_y, target_x, target_y, move_timer
#     slots = []
#     score = 0
#     game_over = False
#     game_won = False
#     remove_card_count = 3  # 撤销道具次数
#     shuffle_count = 3    # 洗牌道具次数
#     undo_history = []    # 撤销历史记录
#     particles = []
#     score_popups = []
#     eliminate_animation = False
#     eliminate_indices = []
#     animation_timer = 0
#     card_moving = False
#     moving_card = None
#     start_x = 0
#     start_y = 0
#     target_x = 0
#     target_y = 0
#     move_timer = 0
#
#     # 初始化卡片堆
#     grid = []
#     for row in range(GRID_ROWS):
#         grid_row = []
#         for col in range(GRID_COLS):
#             layers = random.randint(3, 5)
#             max_card_type = len(card_images) - 1 if card_images else len(COLORS) - 1
#             stack = [random.randint(0, max_card_type) for _ in range(layers)]
#             grid_row.append(stack)
#         grid.append(grid_row)
#
#
# def check_victory(grid):
#     """检查是否胜利"""
#     for row in grid:
#         for stack in row:
#             if len(stack) > 0:
#                 return False
#     return len(slots) == 0
#
#
# def undo_last_move():
#     """撤销上一步操作"""
#     global undo_history, slots, remove_card_count
#     if remove_card_count > 0 and undo_history:
#         # 恢复卡片到原来的位置
#         last_move = undo_history.pop()
#         row, col, card_type = last_move
#         grid[row][col].append(card_type)
#         # 从槽位中移除
#         if slots:
#             slots.pop()
#         remove_card_count -= 1
#
#
# def shuffle_grid():
#     """洗牌功能"""
#     global shuffle_count
#     if shuffle_count > 0:
#         all_cards = []
#         for row in grid:
#             for stack in row:
#                 all_cards.extend(stack)
#                 stack.clear()
#         random.shuffle(all_cards)
#         index = 0
#         for row in grid:
#             for stack in row:
#                 layers = random.randint(1, 3)  # 洗牌后层数减少，使游戏更简单
#                 stack.extend(all_cards[index:index + layers])
#                 index += layers
#         shuffle_count -= 1
#
#
# # 初始化游戏
# init_game()
#
# # 游戏主循环
# clock = pygame.time.Clock()
# running = True
#
# while running:
#     # 事件处理
#     mouse_pos = pygame.mouse.get_pos()
#     restart_button_hover = (
#             RESTART_BUTTON_LEFT <= mouse_pos[0] <= RESTART_BUTTON_LEFT + RESTART_BUTTON_WIDTH and
#             RESTART_BUTTON_TOP <= mouse_pos[1] <= RESTART_BUTTON_TOP + RESTART_BUTTON_HEIGHT
#     )
#
#     # 道具按钮悬停检测
#     undo_button_hover = (
#             ITEM_LEFT <= mouse_pos[0] <= ITEM_LEFT + ITEM_WIDTH and
#             ITEM_TOP <= mouse_pos[1] <= ITEM_TOP + ITEM_HEIGHT
#     )
#
#     shuffle_button_hover = (
#             ITEM_LEFT + ITEM_WIDTH + ITEM_SPACING <= mouse_pos[0] <= ITEM_LEFT + 2 * ITEM_WIDTH + ITEM_SPACING and
#             ITEM_TOP <= mouse_pos[1] <= ITEM_TOP + ITEM_HEIGHT
#     )
#
#     for event in pygame.event.get():
#         if event.type == pygame.QUIT:
#             running = False
#         elif event.type == pygame.MOUSEBUTTONDOWN:
#             if game_over and restart_button_hover:
#                 init_game()
#             elif not game_over:
#                 x, y = event.pos
#                 # 检查是否点击道具按钮
#                 if ITEM_LEFT <= x <= ITEM_LEFT + ITEM_WIDTH and ITEM_TOP <= y <= ITEM_TOP + ITEM_HEIGHT:
#                     undo_last_move()
#                 elif ITEM_LEFT + ITEM_WIDTH + ITEM_SPACING <= x <= ITEM_LEFT + 2 * ITEM_WIDTH + ITEM_SPACING and ITEM_TOP <= y <= ITEM_TOP + ITEM_HEIGHT:
#                     shuffle_grid()
#                 else:
#                     # 计算点击位置
#                     grid_col = (x - GRID_LEFT) // (CARD_WIDTH + SPACING)
#                     grid_row = (y - GRID_TOP) // (CARD_HEIGHT + SPACING)
#                     # 检查点击范围
#                     if 0 <= grid_row < GRID_ROWS and 0 <= grid_col < GRID_COLS:
#                         if len(grid[grid_row][grid_col]) > 0:
#                             # 检查槽位是否已满
#                             if len(slots) >= SLOT_COLS:
#                                 game_over = True
#                                 continue
#
#                             # 记录操作历史用于撤销
#                             card_type = grid[grid_row][grid_col][-1]
#                             undo_history.append((grid_row, grid_col, card_type))
#
#                             # 取出顶层卡片
#                             moving_card = grid[grid_row][grid_col].pop()
#                             start_x = GRID_LEFT + grid_col * (CARD_WIDTH + SPACING)
#                             start_y = GRID_TOP + grid_row * (CARD_HEIGHT + SPACING) + (
#                                 len(grid[grid_row][grid_col])) * OVERLAP_OFFSET
#                             target_x = SLOT_LEFT + len(slots) * (CARD_WIDTH + 5)
#                             target_y = SLOT_TOP
#                             card_moving = True
#                             move_timer = 0
#
#     # 移动背景图
#     bg_x -= BG_MOVE_SPEED
#     if bg_x <= -SCREEN_WIDTH:
#         bg_x = 0
#
#     # 更新粒子效果
#     for particle in particles[:]:
#         particle.update()
#         if particle.life <= 0:
#             particles.remove(particle)
#
#     # 更新得分动画
#     for popup in score_popups[:]:
#         popup.update()
#         if popup.life <= 0:
#             score_popups.remove(popup)
#
#     # 绘制界面
#     if background_img:
#         screen.blit(background_img, (bg_x, 0))
#         screen.blit(background_img, (bg_x + SCREEN_WIDTH, 0))
#     else:
#         screen.fill(BG_COLOR)
#
#     # 绘制标题
#     title_font = pygame.font.SysFont(None, 40)  # 使用默认字体
#     title_text = title_font.render("羊了个羊", True, (0, 0, 0))
#     screen.blit(title_text, (SCREEN_WIDTH // 2 - title_text.get_width() // 2, 50))
#
#     # 绘制卡片堆，添加叠罗汉效果和鼠标悬停放大
#     for row in range(GRID_ROWS):
#         for col in range(GRID_COLS):
#             x = GRID_LEFT + col * (CARD_WIDTH + SPACING)
#             y = GRID_TOP + row * (CARD_HEIGHT + SPACING)
#             stack = grid[row][col]
#             for i, card_type in enumerate(stack):
#                 offset_y = i * OVERLAP_OFFSET
#                 card_x = x
#                 card_y = y + offset_y
#
#                 # 检查鼠标是否悬停在卡片上
#                 mouse_x, mouse_y = pygame.mouse.get_pos()
#                 if (
#                         card_x <= mouse_x <= card_x + CARD_WIDTH
#                         and card_y <= mouse_y <= card_y + CARD_HEIGHT
#                 ):
#                     # 鼠标悬停，放大卡片
#                     scale_factor = 1.2
#                     scaled_width = int(CARD_WIDTH * scale_factor)
#                     scaled_height = int(CARD_HEIGHT * scale_factor)
#                     if card_images:
#                         scaled_img = pygame.transform.scale(card_images[card_type], (scaled_width, scaled_height))
#                         screen.blit(scaled_img, (
#                             card_x - (scaled_width - CARD_WIDTH) // 2,
#                             card_y - (scaled_height - CARD_HEIGHT) // 2
#                         ))
#                     else:
#                         pygame.draw.rect(
#                             screen,
#                             COLORS[card_type],
#                             (
#                                 card_x - (scaled_width - CARD_WIDTH) // 2,
#                                 card_y - (scaled_height - CARD_HEIGHT) // 2,
#                                 scaled_width,
#                                 scaled_height
#                             )
#                         )
#                 else:
#                     if card_images:
#                         screen.blit(card_images[card_type], (card_x, card_y))
#                     else:
#                         pygame.draw.rect(screen, COLORS[card_type], (card_x, card_y, CARD_WIDTH, CARD_HEIGHT))
#
#     # 绘制槽位背景
#     if slot_bg_img:
#         screen.blit(slot_bg_img, (SLOT_LEFT - 10, SLOT_TOP - 10))
#     else:
#         pygame.draw.rect(
#             screen,
#             (200, 200, 200),
#             (SLOT_LEFT - 5, SLOT_TOP - 5, slot_width + 10, SLOT_HEIGHT + 10),
#             border_radius=10
#         )
#
#     # 绘制槽位标题
#     slot_font = pygame.font.SysFont(None, 24)  # 使用默认字体
#     slot_text = slot_font.render("卡槽", True, (0, 0, 0))
#     screen.blit(slot_text, (SLOT_LEFT + slot_width // 2 - slot_text.get_width() // 2, SLOT_TOP - 30))
#
#     # 绘制槽位中的卡片
#     for i, card in enumerate(slots):
#         if eliminate_animation and i in eliminate_indices:
#             # 计算动画进度 (0到1之间)
#             progress = animation_timer / ANIMATION_DURATION
#
#             # 计算卡片位置和大小
#             card_x = SLOT_LEFT + i * (CARD_WIDTH + 5)
#             card_y = SLOT_TOP
#
#             # 添加缩放效果
#             scale = 1 - progress
#             new_width = int(CARD_WIDTH * scale)
#             new_height = int(CARD_HEIGHT * scale)
#
#             # 居中显示缩放后的卡片
#             draw_x = card_x + (CARD_WIDTH - new_width) // 2
#             draw_y = card_y + (CARD_HEIGHT - new_height) // 2
#
#             # 透明度调整
#             alpha = int(255 * (1 - progress))
#
#             if card_images:
#                 # 创建卡片的临时副本并设置透明度
#                 img = card_images[card].copy()
#                 img = pygame.transform.scale(img, (new_width, new_height))
#                 img.set_alpha(alpha)
#                 screen.blit(img, (draw_x, draw_y))
#             else:
#                 surface = pygame.Surface((new_width, new_height), pygame.SRCALPHA)
#                 surface.fill((*COLORS[card], alpha))
#                 screen.blit(surface, (draw_x, draw_y))
#
#             # 在动画结束前创建粒子效果
#             if progress > 0.7:
#                 if random.random() < 0.3:
#                     color = COLORS[card] if not card_images else (255, 255, 255)
#                     for _ in range(3):
#                         particles.append(Particle(
#                             draw_x + new_width // 2,
#                             draw_y + new_height // 2,
#                             color
#                         ))
#         else:
#             x = SLOT_LEFT + i * (CARD_WIDTH + 5)
#             if card_images:
#                 screen.blit(card_images[card], (x, SLOT_TOP))
#             else:
#                 pygame.draw.rect(screen, COLORS[card], (x, SLOT_TOP, CARD_WIDTH, CARD_HEIGHT))
#
#     # 处理卡片移动动画
#     if card_moving:
#         progress = move_timer / MOVE_DURATION
#         # 使用平滑的缓动函数替代线性插值
#         ease_progress = 0.5 - 0.5 * math.cos(progress * math.pi)
#         current_x = start_x + (target_x - start_x) * ease_progress
#         current_y = start_y + (target_y - start_y) * ease_progress
#         if card_images:
#             screen.blit(card_images[moving_card], (current_x, current_y))
#         else:
#             pygame.draw.rect(screen, COLORS[moving_card], (current_x, current_y, CARD_WIDTH, CARD_HEIGHT))
#         move_timer += 1
#         if move_timer >= MOVE_DURATION:
#             slots.append(moving_card)
#             card_moving = False
#             moving_card = None
#             # 检查连续三个相同卡片
#             if len(slots) >= 3 and slots[-1] == slots[-2] == slots[-3]:
#                 eliminate_animation = True
#                 eliminate_indices = [len(slots) - 3, len(slots) - 2, len(slots) - 1]
#                 animation_timer = 0
#                 score += 1
#                 # 创建得分动画
#                 score_popups.append(ScorePopup(
#                     SLOT_LEFT + (len(slots) - 2) * (CARD_WIDTH + 5),
#                     SLOT_TOP - 30
#                 ))
#
#             # 再次检查槽位是否已满
#             if len(slots) >= SLOT_COLS:
#                 game_over = True
#
#             # 检查胜利条件
#             if check_victory(grid):
#                 game_won = True
#                 game_over = True
#
#     # 处理消去动画
#     if eliminate_animation:
#         animation_timer += 1
#         if animation_timer >= ANIMATION_DURATION:
#             # 从后向前删除，避免索引变化问题
#             for i in sorted(eliminate_indices, reverse=True):
#                 del slots[i]
#             eliminate_animation = False
#             animation_timer = 0
#             eliminate_indices = []
#
#     # 绘制粒子效果
#     for particle in particles:
#         particle.draw(screen)
#
#     # 绘制得分动画
#     for popup in score_popups:
#         popup.draw(screen)
#
#     # 绘制状态信息
#     status_font = pygame.font.SysFont(None, 28)  # 使用默认字体
#     score_text = status_font.render(f"得分: {score}", True, TEXT_COLOR)
#     screen.blit(score_text, (20, 20))
#
#     # 绘制槽位容量提示
#     capacity_font = pygame.font.SysFont(None, 28)  # 使用默认字体
#     capacity_text = capacity_font.render(f"已用: {len(slots)}/{SLOT_COLS}", True, CAPACITY_COLOR)
#     screen.blit(capacity_text, (SCREEN_WIDTH - capacity_text.get_width() - 20, 20))
#
#     # 绘制道具按钮
#     # 撤销道具按钮
#     if undo_button_img:
#         if undo_button_hover:
#             screen.blit(undo_button_hover_img, (
#                 ITEM_LEFT - (undo_button_hover_img.get_width() - ITEM_WIDTH) // 2,
#                 ITEM_TOP - (undo_button_hover_img.get_height() - ITEM_HEIGHT) // 2
#             ))
#         else:
#             screen.blit(undo_button_img, (ITEM_LEFT, ITEM_TOP))
#     else:
#         pygame.draw.rect(
#             screen,
#             ITEM_COLOR_1 if not undo_button_hover else (0, 168, 0),
#             (ITEM_LEFT, ITEM_TOP, ITEM_WIDTH, ITEM_HEIGHT),
#             border_radius=5
#         )
#         # 绘制撤销图标
#         undo_font = pygame.font.SysFont(None, 24)  # 使用默认字体
#         undo_text = undo_font.render("撤销", True, ITEM_TEXT_COLOR)
#         screen.blit(undo_text, (ITEM_LEFT + 10, ITEM_TOP + 18))
#
#     # 洗牌道具按钮
#     if shuffle_button_img:
#         if shuffle_button_hover:
#             screen.blit(shuffle_button_hover_img, (
#                 ITEM_LEFT + ITEM_WIDTH + ITEM_SPACING - (shuffle_button_hover_img.get_width() - ITEM_WIDTH) // 2,
#                 ITEM_TOP - (shuffle_button_hover_img.get_height() - ITEM_HEIGHT) // 2
#             ))
#         else:
#             screen.blit(shuffle_button_img, (ITEM_LEFT + ITEM_WIDTH + ITEM_SPACING, ITEM_TOP))
#     else:
#         pygame.draw.rect(
#             screen,
#             ITEM_COLOR_2 if not shuffle_button_hover else (0, 0, 168),
#             (ITEM_LEFT + ITEM_WIDTH + ITEM_SPACING, ITEM_TOP, ITEM_WIDTH, ITEM_HEIGHT),
#             border_radius=5
#         )
#         # 绘制洗牌图标
#         shuffle_font = pygame.font.SysFont(None, 24)  # 使用默认字体
#         shuffle_text = shuffle_font.render("洗牌", True, ITEM_TEXT_COLOR)
#         screen.blit(shuffle_text, (ITEM_LEFT + ITEM_WIDTH + ITEM_SPACING + 10, ITEM_TOP + 18))
#
#     # 绘制道具剩余次数
#     item_font = pygame.font.SysFont(None, 18)  # 使用默认字体
#     undo_count_text = item_font.render(f"x{remove_card_count}", True, ITEM_TEXT_COLOR)
#     shuffle_count_text = item_font.render(f"x{shuffle_count}", True, ITEM_TEXT_COLOR)
#     screen.blit(undo_count_text, (ITEM_LEFT + ITEM_WIDTH - undo_count_text.get_width() - 5, ITEM_TOP + ITEM_HEIGHT - undo_count_text.get_height() - 5))
#     screen.blit(shuffle_count_text, (ITEM_LEFT + 2 * ITEM_WIDTH + ITEM_SPACING - shuffle_count_text.get_width() - 5, ITEM_TOP + ITEM_HEIGHT - shuffle_count_text.get_height() - 5))
#
#
#
#
#     # 游戏结束时显示结果和重玩按钮
#     if game_over:
#         # 绘制半透明遮罩
#         overlay = pygame.Surface((SCREEN_WIDTH, SCREEN_HEIGHT), pygame.SRCALPHA)
#         overlay.fill((0, 0, 0, 128))
#         screen.blit(overlay, (0, 0))
#
#         # 绘制游戏结果
#         result_font = pygame.font.SysFont(None, 50)  # 使用默认字体
#         result_text = result_font.render("恭喜你赢了!" if game_won else "游戏结束!",
#                                          True, WIN_COLOR if game_won else LOSE_COLOR)
#         screen.blit(result_text, (SCREEN_WIDTH // 2 - result_text.get_width() // 2, SCREEN_HEIGHT // 2 - 70))
#
#         # 绘制最终得分
#         final_score_font = pygame.font.SysFont(None, 36)  # 使用默认字体
#         final_score_text = final_score_font.render(f"最终得分: {score}", True, (255, 255, 255))
#         screen.blit(final_score_text, (SCREEN_WIDTH // 2 - final_score_text.get_width() // 2, SCREEN_HEIGHT // 2 - 20))
#
#         # 绘制重玩按钮
#         if restart_button_img:
#             if restart_button_hover:
#                 screen.blit(restart_button_hover_img, (
#                     RESTART_BUTTON_LEFT - (restart_button_hover_img.get_width() - RESTART_BUTTON_WIDTH) // 2,
#                     RESTART_BUTTON_TOP - (restart_button_hover_img.get_height() - RESTART_BUTTON_HEIGHT) // 2
#                 ))
#             else:
#                 screen.blit(restart_button_img, (RESTART_BUTTON_LEFT, RESTART_BUTTON_TOP))
#         else:
#             pygame.draw.rect(
#                 screen,
#                 BUTTON_HOVER_COLOR if restart_button_hover else BUTTON_COLOR,
#                 (RESTART_BUTTON_LEFT, RESTART_BUTTON_TOP, RESTART_BUTTON_WIDTH, RESTART_BUTTON_HEIGHT),
#                 border_radius=10
#             )
#             restart_text = pygame.font.SysFont(None, 36).render("再玩一次", True, BUTTON_TEXT_COLOR)  # 使用默认字体
#             screen.blit(
#                 restart_text,
#                 (
#                     RESTART_BUTTON_LEFT + (RESTART_BUTTON_WIDTH - restart_text.get_width()) // 2,
#                     RESTART_BUTTON_TOP + (RESTART_BUTTON_HEIGHT - restart_text.get_height()) // 2
#                 )
#             )
#
#     pygame.display.flip()
#     clock.tick(90)
#
# pygame.quit()
#
#
#
#
# import pygame
# import random
# import os
# import math
# from datetime import datetime  # 添加时间模块
#
# # 初始化Pygame
# pygame.init()
#
# # 游戏窗口设置
# SCREEN_WIDTH = 480
# SCREEN_HEIGHT = 720
# screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
# pygame.display.set_caption("羊了个羊")
#
# # 颜色定义
# BG_COLOR = (255, 255, 255)
# TEXT_COLOR = (0, 0, 0)
# CAPACITY_COLOR = (100, 100, 100)
# ITEM_COLOR_1 = (0, 128, 0)  # 撤销道具颜色
# ITEM_COLOR_2 = (0, 0, 128)  # 洗牌道具颜色
# ITEM_TEXT_COLOR = (255, 255, 255)
# WIN_COLOR = (0, 128, 0)  # 胜利文字颜色
# LOSE_COLOR = (255, 0, 0)  # 失败文字颜色
# BUTTON_COLOR = (65, 105, 225)  # 按钮背景色
# BUTTON_HOVER_COLOR = (70, 130, 180)  # 按钮悬停色
# BUTTON_TEXT_COLOR = (255, 255, 255)  # 按钮文字颜色
# TIMER_COLOR = (255, 0, 0)  # 计时文字颜色
#
# # 卡片尺寸和间距
# CARD_WIDTH = 50
# CARD_HEIGHT = 60
# SPACING = 10
# # 叠罗汉偏移量
# OVERLAP_OFFSET = 4
#
# # 游戏区域布局
# GRID_ROWS = 6
# GRID_COLS = 6
# grid_width = GRID_COLS * (CARD_WIDTH + SPACING) - SPACING
# GRID_LEFT = (SCREEN_WIDTH - grid_width) // 2
# GRID_TOP = 100
#
# # 槽位区域设置
# SLOT_ROWS = 1
# SLOT_COLS = 7  # 最多存放7个卡片
# slot_width = SLOT_COLS * (CARD_WIDTH + 5) - 5
# SLOT_LEFT = (SCREEN_WIDTH - slot_width) // 2
# SLOT_TOP = SCREEN_HEIGHT - CARD_HEIGHT - 50
# SLOT_HEIGHT = CARD_HEIGHT + 20
#
# # 道具按钮设置
# ITEM_WIDTH = 60  # 道具按钮宽度
# ITEM_HEIGHT = 60  # 道具按钮高度
# ITEM_SPACING = 20  # 道具按钮间距
# ITEM_TOP = 20  # 道具按钮顶部位置
# ITEM_LEFT = (SCREEN_WIDTH - (2 * ITEM_WIDTH + ITEM_SPACING)) // 2  # 道具按钮左侧起始位置
#
# # 重玩按钮设置
# RESTART_BUTTON_WIDTH = 150
# RESTART_BUTTON_HEIGHT = 50
# RESTART_BUTTON_LEFT = (SCREEN_WIDTH - RESTART_BUTTON_WIDTH) // 2
# RESTART_BUTTON_TOP = SCREEN_HEIGHT // 2 + 50
#
# # 动画常量
# ANIMATION_DURATION = 30  # 消去动画持续时间
# MOVE_DURATION = 20  # 卡片移动动画持续时间
#
# # 新增计时相关变量
# start_time = None  # 开始时间
# elapsed_time = 0  # 总耗时（秒）
# is_paused = False  # 暂停状态
#
# # 加载背景图像
# try:
#     image_folder = os.path.join(os.path.dirname(__file__), "image")
#     background_path = os.path.join(image_folder, "back.png")
#     background_img = pygame.image.load(background_path)
#     background_img = pygame.transform.scale(background_img, (SCREEN_WIDTH * 2, SCREEN_HEIGHT))
#     print("主背景图像加载成功")
#     bg_x = 0
#     BG_MOVE_SPEED = 1
# except Exception as e:
#     print(f"主背景图像加载失败: {e}")
#     background_img = None
#     bg_x = 0
#
# # 加载槽位背景图像
# try:
#     slot_bg_path = os.path.join(image_folder, "back2.png")
#     slot_bg_img = pygame.image.load(slot_bg_path)
#     slot_bg_img = pygame.transform.scale(slot_bg_img, (slot_width + 20, SLOT_HEIGHT + 20))
#     print("槽位背景图像加载成功")
# except Exception as e:
#     print(f"槽位背景图像加载失败: {e}")
#     slot_bg_img = None
#
# # 加载卡片图片
# card_images = []
# try:
#     for i in range(7):
#         if i == 0:
#             tile_path = os.path.join(image_folder, "tile.png")
#         else:
#             tile_path = os.path.join(image_folder, f"tile{i}.png")
#
#         if os.path.exists(tile_path):
#             img = pygame.image.load(tile_path)
#             img = pygame.transform.scale(img, (CARD_WIDTH, CARD_HEIGHT))
#             card_images.append(img)
#             print(f"卡片图片 {os.path.basename(tile_path)} 加载成功")
#         else:
#             print(f"卡片图片 {tile_path} 不存在")
#
#     if not card_images:
#         raise Exception("没有找到任何卡片图片")
#
# except Exception as e:
#     print(f"卡片图片加载失败: {e}")
#     COLORS = [
#         (255, 0, 0),  # 红
#         (0, 255, 0),  # 绿
#         (0, 0, 255),  # 蓝
#         (255, 255, 0),  # 黄
#         (128, 0, 128),  # 紫
#         (255, 165, 0),  # 橙
#         (0, 191, 255),  # 天蓝
#     ]
#
# # 加载道具按钮图片
# try:
#     # 撤销道具图片 (tuixiao.PNG)
#     undo_img_path = os.path.join(image_folder, "chexiao.PNG")
#     undo_button_img = pygame.image.load(undo_img_path)
#     undo_button_img = pygame.transform.scale(undo_button_img, (ITEM_WIDTH, ITEM_HEIGHT))
#     undo_button_hover_img = pygame.transform.scale(undo_button_img, (ITEM_WIDTH + 5, ITEM_HEIGHT + 5))
#     print("撤销道具图片加载成功")
# except Exception as e:
#     print(f"撤销道具图片加载失败: {e}")
#     undo_button_img = None
#     undo_button_hover_img = None
#
# try:
#     # 洗牌道具图片 (xipai.PNG)
#     shuffle_img_path = os.path.join(image_folder, "xipai.PNG")
#     shuffle_button_img = pygame.image.load(shuffle_img_path)
#     shuffle_button_img = pygame.transform.scale(shuffle_button_img, (ITEM_WIDTH, ITEM_HEIGHT))
#     shuffle_button_hover_img = pygame.transform.scale(shuffle_button_img, (ITEM_WIDTH + 5, ITEM_HEIGHT + 5))
#     print("洗牌道具图片加载成功")
# except Exception as e:
#     print(f"洗牌道具图片加载失败: {e}")
#     shuffle_button_img = None
#     shuffle_button_hover_img = None
#
# # 加载重玩按钮图片
# try:
#     restart_img_path = os.path.join(image_folder, "chongwan.PNG")
#     restart_button_img = pygame.image.load(restart_img_path)
#     restart_button_img = pygame.transform.scale(restart_button_img, (RESTART_BUTTON_WIDTH, RESTART_BUTTON_HEIGHT))
#     restart_button_hover_img = pygame.transform.scale(restart_button_img,
#                                                       (RESTART_BUTTON_WIDTH + 5, RESTART_BUTTON_HEIGHT + 5))
#     print("重玩按钮图片加载成功")
# except Exception as e:
#     print(f"重玩按钮图片加载失败: {e}")
#     restart_button_img = None
#     restart_button_hover_img = None
#
#
# # 粒子效果类
# class Particle:
#     def __init__(self, x, y, color):
#         self.x = x
#         self.y = y
#         self.color = color
#         self.radius = random.randint(2, 5)
#         self.speed_x = random.uniform(-3, 3)
#         self.speed_y = random.uniform(-5, -1)
#         self.gravity = 0.1
#         self.life = random.randint(20, 40)
#
#     def update(self):
#         self.x += self.speed_x
#         self.y += self.speed_y
#         self.speed_y += self.gravity
#         self.life -= 1
#
#     def draw(self, surface):
#         alpha = int((self.life / 40) * 255)
#         if alpha > 0:
#             s = pygame.Surface((self.radius * 2, self.radius * 2), pygame.SRCALPHA)
#             pygame.draw.circle(s, (*self.color, alpha), (self.radius, self.radius), self.radius)
#             surface.blit(s, (int(self.x - self.radius), int(self.y - self.radius)))
#
#
# # 得分增加动画类
# class ScorePopup:
#     def __init__(self, x, y):
#         self.x = x
#         self.y = y
#         self.value = "+1"
#         self.font = pygame.font.SysFont(None, 30)  # 使用默认字体
#         self.color = (255, 215, 0)  # 金色
#         self.life = 40
#         self.speed_y = -1
#
#     def update(self):
#         self.y += self.speed_y
#         self.life -= 1
#
#     def draw(self, surface):
#         alpha = int((self.life / 40) * 255)
#         if alpha > 0:
#             text = self.font.render(self.value, True, self.color)
#             text.set_alpha(alpha)
#             surface.blit(text, (self.x, self.y))
#
#
# # 初始化游戏函数
# def init_game():
#     global slots, score, game_over, game_won, grid, undo_history, remove_card_count, shuffle_count, particles, score_popups, eliminate_animation, eliminate_indices, animation_timer, card_moving, moving_card, start_x, start_y, target_x, target_y, move_timer
#     global start_time, elapsed_time, is_paused  # 新增计时变量初始化
#
#     slots = []
#     score = 0
#     game_over = False
#     game_won = False
#     remove_card_count = 3  # 撤销道具次数
#     shuffle_count = 3  # 洗牌道具次数
#     undo_history = []  # 撤销历史记录
#     particles = []
#     score_popups = []
#     eliminate_animation = False
#     eliminate_indices = []
#     animation_timer = 0
#     card_moving = False
#     moving_card = None
#     start_x = 0
#     start_y = 0
#     target_x = 0
#     target_y = 0
#     move_timer = 0
#
#     # 初始化网格
#     grid = []
#     for row in range(GRID_ROWS):
#         grid_row = []
#         for col in range(GRID_COLS):
#             # 为每个网格位置创建一个卡片堆
#             # 初始时，每个位置有0-3张卡片
#             stack_size = random.randint(0, 3)
#             stack = [random.randint(0, 6) for _ in range(stack_size)]
#             grid_row.append(stack)
#         grid.append(grid_row)
#
#     # 确保游戏中有足够的卡片可玩
#     # 这里可以添加更复杂的卡片生成逻辑
#
#     # 计时初始化
#     start_time = datetime.now()  # 开始新游戏时记录开始时间
#     elapsed_time = 0
#     is_paused = False
#
#
# # 检查胜利条件
# def check_victory(grid):
#     # 检查网格中是否所有卡片都已被移除
#     for row in grid:
#         for stack in row:
#             if len(stack) > 0:
#                 return False
#     return True
#
#
# # 撤销上次操作
# def undo_last_move():
#     global remove_card_count, slots, grid
#
#     if remove_card_count <= 0:
#         return  # 没有撤销次数了
#
#     if not undo_history:
#         return  # 没有历史记录可撤销
#
#     # 获取最后一次操作
#     row, col, card_type = undo_history.pop()
#
#     # 将卡片放回网格
#     grid[row][col].append(card_type)
#
#     # 从槽位移除卡片
#     if slots:
#         slots.pop()
#
#     # 减少撤销次数
#     remove_card_count -= 1
#
#
# # 洗牌函数
# def shuffle_grid():
#     global shuffle_count, grid
#
#     if shuffle_count <= 0:
#         return  # 没有洗牌次数了
#
#     # 收集所有卡片
#     all_cards = []
#     for row in grid:
#         for stack in row:
#             all_cards.extend(stack)
#             stack.clear()  # 清空所有堆
#
#     # 洗牌
#     random.shuffle(all_cards)
#
#     # 重新分配卡片到网格
#     index = 0
#     for row in range(GRID_ROWS):
#         for col in range(GRID_COLS):
#             stack_size = min(random.randint(0, 3), len(all_cards) - index)
#             grid[row][col] = all_cards[index:index + stack_size]
#             index += stack_size
#
#     # 减少洗牌次数
#     shuffle_count -= 1
#
#
# # 初始化游戏
# init_game()
#
# # 游戏主循环
# clock = pygame.time.Clock()
# running = True
#
# while running:
#     # 事件处理新增计时控制
#     mouse_pos = pygame.mouse.get_pos()
#     restart_button_hover = (
#             RESTART_BUTTON_LEFT <= mouse_pos[0] <= RESTART_BUTTON_LEFT + RESTART_BUTTON_WIDTH and
#             RESTART_BUTTON_TOP <= mouse_pos[1] <= RESTART_BUTTON_TOP + RESTART_BUTTON_HEIGHT
#     )
#
#     # 道具按钮悬停检测
#     undo_button_hover = (
#             ITEM_LEFT <= mouse_pos[0] <= ITEM_LEFT + ITEM_WIDTH and
#             ITEM_TOP <= mouse_pos[1] <= ITEM_TOP + ITEM_HEIGHT
#     )
#
#     shuffle_button_hover = (
#             ITEM_LEFT + ITEM_WIDTH + ITEM_SPACING <= mouse_pos[0] <= ITEM_LEFT + 2 * ITEM_WIDTH + ITEM_SPACING and
#             ITEM_TOP <= mouse_pos[1] <= ITEM_TOP + ITEM_HEIGHT
#     )
#
#     for event in pygame.event.get():
#         if event.type == pygame.QUIT:
#             running = False
#         elif event.type == pygame.MOUSEBUTTONDOWN:
#             if game_over and restart_button_hover:
#                 init_game()
#             elif not game_over:
#                 x, y = event.pos
#                 # 检查是否点击道具按钮
#                 if ITEM_LEFT <= x <= ITEM_LEFT + ITEM_WIDTH and ITEM_TOP <= y <= ITEM_TOP + ITEM_HEIGHT:
#                     undo_last_move()
#                 elif ITEM_LEFT + ITEM_WIDTH + ITEM_SPACING <= x <= ITEM_LEFT + 2 * ITEM_WIDTH + ITEM_SPACING and ITEM_TOP <= y <= ITEM_TOP + ITEM_HEIGHT:
#                     shuffle_grid()
#                 else:
#                     # 计算点击位置
#                     grid_col = (x - GRID_LEFT) // (CARD_WIDTH + SPACING)
#                     grid_row = (y - GRID_TOP) // (CARD_HEIGHT + SPACING)
#                     # 检查点击范围
#                     if 0 <= grid_row < GRID_ROWS and 0 <= grid_col < GRID_COLS:
#                         if len(grid[grid_row][grid_col]) > 0:
#                             # 检查槽位是否已满
#                             if len(slots) >= SLOT_COLS:
#                                 game_over = True
#                                 continue
#
#                             # 记录操作历史用于撤销
#                             card_type = grid[grid_row][grid_col][-1]
#                             undo_history.append((grid_row, grid_col, card_type))
#
#                             # 取出顶层卡片
#                             moving_card = grid[grid_row][grid_col].pop()
#                             start_x = GRID_LEFT + grid_col * (CARD_WIDTH + SPACING)
#                             start_y = GRID_TOP + grid_row * (CARD_HEIGHT + SPACING) + (
#                                 len(grid[grid_row][grid_col])) * OVERLAP_OFFSET
#                             target_x = SLOT_LEFT + len(slots) * (CARD_WIDTH + 5)
#                             target_y = SLOT_TOP
#                             card_moving = True
#                             move_timer = 0
#
#                             # 确保游戏开始后才计时
#                             if not start_time:
#                                 start_time = datetime.now()
#
#         # 新增：游戏暂停/继续控制（按P键）
#         elif event.type == pygame.KEYDOWN:
#             if event.key == pygame.K_p and not game_over:
#                 is_paused = not is_paused
#                 if not is_paused and start_time:
#                     # 恢复计时时调整开始时间
#                     pause_duration = (datetime.now() - pause_start_time).total_seconds()
#                     start_time = datetime.now() - datetime.timedelta(seconds=pause_duration)
#             elif event.key == pygame.K_r and game_over:  # 新增按R键重新开始
#                 init_game()
#
#     # 移动背景图
#     bg_x -= BG_MOVE_SPEED
#     if bg_x <= -SCREEN_WIDTH:
#         bg_x = 0
#
#     # 计算 elapsed_time（仅在游戏进行中更新）
#     if start_time and not game_over and not is_paused:
#         current_time = datetime.now()
#         elapsed_time = (current_time - start_time).total_seconds()
#
#     # 更新粒子效果
#     for particle in particles[:]:
#         particle.update()
#         if particle.life <= 0:
#             particles.remove(particle)
#
#     # 更新得分动画
#     for popup in score_popups[:]:
#         popup.update()
#         if popup.life <= 0:
#             score_popups.remove(popup)
#
#     # 绘制界面
#     if background_img:
#         screen.blit(background_img, (bg_x, 0))
#         screen.blit(background_img, (bg_x + SCREEN_WIDTH, 0))
#     else:
#         screen.fill(BG_COLOR)
#
#     # 绘制标题
#     title_font = pygame.font.SysFont(None, 40)  # 使用默认字体
#     title_text = title_font.render("羊了个羊", True, (0, 0, 0))
#     screen.blit(title_text, (SCREEN_WIDTH // 2 - title_text.get_width() // 2, 50))
#
#     # 绘制卡片堆，添加叠罗汉效果和鼠标悬停放大
#     for row in range(GRID_ROWS):
#         for col in range(GRID_COLS):
#             x = GRID_LEFT + col * (CARD_WIDTH + SPACING)
#             y = GRID_TOP + row * (CARD_HEIGHT + SPACING)
#             stack = grid[row][col]
#             for i, card_type in enumerate(stack):
#                 offset_y = i * OVERLAP_OFFSET
#                 card_x = x
#                 card_y = y + offset_y
#
#                 # 检查鼠标是否悬停在卡片上
#                 mouse_x, mouse_y = pygame.mouse.get_pos()
#                 if (
#                         card_x <= mouse_x <= card_x + CARD_WIDTH
#                         and card_y <= mouse_y <= card_y + CARD_HEIGHT
#                 ):
#                     # 鼠标悬停，放大卡片
#                     scale_factor = 1.2
#                     scaled_width = int(CARD_WIDTH * scale_factor)
#                     scaled_height = int(CARD_HEIGHT * scale_factor)
#                     if card_images:
#                         scaled_img = pygame.transform.scale(card_images[card_type], (scaled_width, scaled_height))
#                         screen.blit(scaled_img, (
#                             card_x - (scaled_width - CARD_WIDTH) // 2,
#                             card_y - (scaled_height - CARD_HEIGHT) // 2
#                         ))
#                     else:
#                         pygame.draw.rect(
#                             screen,
#                             COLORS[card_type],
#                             (
#                                 card_x - (scaled_width - CARD_WIDTH) // 2,
#                                 card_y - (scaled_height - CARD_HEIGHT) // 2,
#                                 scaled_width,
#                                 scaled_height
#                             )
#                         )
#                 else:
#                     if card_images:
#                         screen.blit(card_images[card_type], (card_x, card_y))
#                     else:
#                         pygame.draw.rect(screen, COLORS[card_type], (card_x, card_y, CARD_WIDTH, CARD_HEIGHT))
#
#     # 绘制槽位背景
#     if slot_bg_img:
#         screen.blit(slot_bg_img, (SLOT_LEFT - 10, SLOT_TOP - 10))
#     else:
#         pygame.draw.rect(
#             screen,
#             (200, 200, 200),
#             (SLOT_LEFT - 5, SLOT_TOP - 5, slot_width + 10, SLOT_HEIGHT + 10),
#             border_radius=10
#         )
#
#     # 绘制槽位标题
#     slot_font = pygame.font.SysFont(None, 24)  # 使用默认字体
#     slot_text = slot_font.render("卡槽", True, (0, 0, 0))
#     screen.blit(slot_text, (SLOT_LEFT + slot_width // 2 - slot_text.get_width() // 2, SLOT_TOP - 30))
#
#     # 绘制槽位中的卡片
#     for i, card in enumerate(slots):
#         if eliminate_animation and i in eliminate_indices:
#             # 计算动画进度 (0到1之间)
#             progress = animation_timer / ANIMATION_DURATION
#
#             # 计算卡片位置和大小
#             card_x = SLOT_LEFT + i * (CARD_WIDTH + 5)
#             card_y = SLOT_TOP
#
#             # 添加缩放效果
#             scale = 1 - progress
#             new_width = int(CARD_WIDTH * scale)
#             new_height = int(CARD_HEIGHT * scale)
#
#             # 居中显示缩放后的卡片
#             draw_x = card_x + (CARD_WIDTH - new_width) // 2
#             draw_y = card_y + (CARD_HEIGHT - new_height) // 2
#
#             # 透明度调整
#             alpha = int(255 * (1 - progress))
#
#             if card_images:
#                 # 创建卡片的临时副本并设置透明度
#                 img = card_images[card].copy()
#                 img = pygame.transform.scale(img, (new_width, new_height))
#                 img.set_alpha(alpha)
#                 screen.blit(img, (draw_x, draw_y))
#             else:
#                 surface = pygame.Surface((new_width, new_height), pygame.SRCALPHA)
#                 surface.fill((*COLORS[card], alpha))
#                 screen.blit(surface, (draw_x, draw_y))
#
#             # 在动画结束前创建粒子效果
#             if progress > 0.7:
#                 if random.random() < 0.3:
#                     color = COLORS[card] if not card_images else (255, 255, 255)
#                     for _ in range(3):
#                         particles.append(Particle(
#                             draw_x + new_width // 2,
#                             draw_y + new_height // 2,
#                             color
#                         ))
#         else:
#             x = SLOT_LEFT + i * (CARD_WIDTH + 5)
#             if card_images:
#                 screen.blit(card_images[card], (x, SLOT_TOP))
#             else:
#                 pygame.draw.rect(screen, COLORS[card], (x, SLOT_TOP, CARD_WIDTH, CARD_HEIGHT))
#
#     # 处理卡片移动动画
#     if card_moving:
#         progress = move_timer / MOVE_DURATION
#         # 使用平滑的缓动函数替代线性插值
#         ease_progress = 0.5 - 0.5 * math.cos(progress * math.pi)
#         current_x = start_x + (target_x - start_x) * ease_progress
#         current_y = start_y + (target_y - start_y) * ease_progress
#         if card_images:
#             screen.blit(card_images[moving_card], (current_x, current_y))
#         else:
#             pygame.draw.rect(screen, COLORS[moving_card], (current_x, current_y, CARD_WIDTH, CARD_HEIGHT))
#         move_timer += 1
#         if move_timer >= MOVE_DURATION:
#             slots.append(moving_card)
#             card_moving = False
#             moving_card = None
#             # 检查连续三个相同卡片
#             if len(slots) >= 3 and slots[-1] == slots[-2] == slots[-3]:
#                 eliminate_animation = True
#                 eliminate_indices = [len(slots) - 3, len(slots) - 2, len(slots) - 1]
#                 animation_timer = 0
#                 score += 1
#                 # 创建得分动画
#                 score_popups.append(ScorePopup(
#                     SLOT_LEFT + (len(slots) - 2) * (CARD_WIDTH + 5),
#                     SLOT_TOP - 30
#                 ))
#
#             # 再次检查槽位是否已满
#             if len(slots) >= SLOT_COLS:
#                 game_over = True
#
#             # 检查胜利条件
#             if check_victory(grid):
#                 game_won = True
#                 game_over = True
#
#     # 处理消去动画
#     if eliminate_animation:
#         animation_timer += 1
#         if animation_timer >= ANIMATION_DURATION:
#             # 从后向前删除，避免索引变化问题
#             for i in sorted(eliminate_indices, reverse=True):
#                 del slots[i]
#             eliminate_animation = False
#             animation_timer = 0
#             eliminate_indices = []
#
#     # 绘制粒子效果
#     for particle in particles:
#         particle.draw(screen)
#
#     # 绘制得分动画
#     for popup in score_popups:
#         popup.draw(screen)
#
#     # 绘制状态信息
#     status_font = pygame.font.SysFont(None, 28)  # 使用默认字体
#     score_text = status_font.render(f"得分: {score}", True, TEXT_COLOR)
#     screen.blit(score_text, (20, 20))
#
#     # 绘制计时文本
#     timer_font = pygame.font.SysFont(None, 36)
#     minutes = int(elapsed_time // 60)
#     seconds = int(elapsed_time % 60)
#     timer_text = timer_font.render(f"时间: {minutes:02d}:{seconds:02d}", True, TIMER_COLOR)
#     screen.blit(timer_text, (20, 60))  # 显示在得分下方
#
#     # 绘制暂停提示（仅在暂停时显示）
#     if is_paused and not game_over:
#         pause_font = pygame.font.SysFont(None, 48)
#         pause_text = pause_font.render("已暂停 (按P继续)", True, (255, 0, 0))
#         screen.blit(pause_text, (SCREEN_WIDTH // 2 - pause_text.get_width() // 2, SCREEN_HEIGHT // 2 - 24))
#
#     # 绘制槽位容量提示
#     capacity_font = pygame.font.SysFont(None, 28)  # 使用默认字体
#     capacity_text = capacity_font.render(f"已用: {len(slots)}/{SLOT_COLS}", True, CAPACITY_COLOR)
#     screen.blit(capacity_text, (SCREEN_WIDTH - capacity_text.get_width() - 20, 20))
#
#     # 绘制道具按钮
#     # 撤销道具按钮
#     if undo_button_img:
#         if undo_button_hover:
#             screen.blit(undo_button_hover_img, (
#                 ITEM_LEFT - (undo_button_hover_img.get_width() - ITEM_WIDTH) // 2,
#                 ITEM_TOP - (undo_button_hover_img.get_height() - ITEM_HEIGHT) // 2
#             ))
#         else:
#             screen.blit(undo_button_img, (ITEM_LEFT, ITEM_TOP))
#     else:
#         pygame.draw.rect(
#             screen,
#             ITEM_COLOR_1 if not undo_button_hover else (0, 168, 0),
#             (ITEM_LEFT, ITEM_TOP, ITEM_WIDTH, ITEM_HEIGHT),
#             border_radius=5
#         )
#         # 绘制撤销图标
#         undo_font = pygame.font.SysFont(None, 24)  # 使用默认字体
#         undo_text = undo_font.render("撤销", True, ITEM_TEXT_COLOR)
#         screen.blit(undo_text, (ITEM_LEFT + 10, ITEM_TOP + 18))
#
#     # 洗牌道具按钮
#     if shuffle_button_img:
#         if shuffle_button_hover:
#             screen.blit(shuffle_button_hover_img, (
#                 ITEM_LEFT + ITEM_WIDTH + ITEM_SPACING - (shuffle_button_hover_img.get_width() - ITEM_WIDTH) // 2,
#                 ITEM_TOP - (shuffle_button_hover_img.get_height() - ITEM_HEIGHT) // 2
#             ))
#         else:
#             screen.blit(shuffle_button_img, (ITEM_LEFT + ITEM_WIDTH + ITEM_SPACING, ITEM_TOP))
#     else:
#         pygame.draw.rect(
#             screen,
#             ITEM_COLOR_2 if not shuffle_button_hover else (0, 0, 168),
#             (ITEM_LEFT + ITEM_WIDTH + ITEM_SPACING, ITEM_TOP, ITEM_WIDTH, ITEM_HEIGHT),
#             border_radius=5
#         )
#         # 绘制洗牌图标
#         shuffle_font = pygame.font.SysFont(None, 24)  # 使用默认字体
#         shuffle_text = shuffle_font.render("洗牌", True, ITEM_TEXT_COLOR)
#         screen.blit(shuffle_text, (ITEM_LEFT + ITEM_WIDTH + ITEM_SPACING + 10, ITEM_TOP + 18))
#
#     # 绘制道具剩余次数
#     item_font = pygame.font.SysFont(None, 18)  # 使用默认字体
#     undo_count_text = item_font.render(f"x{remove_card_count}", True, ITEM_TEXT_COLOR)
#     shuffle_count_text = item_font.render(f"x{shuffle_count}", True, ITEM_TEXT_COLOR)
#     screen.blit(undo_count_text, (ITEM_LEFT + ITEM_WIDTH - undo_count_text.get_width() - 5,
#                                   ITEM_TOP + ITEM_HEIGHT - undo_count_text.get_height() - 5))
#     screen.blit(shuffle_count_text, (ITEM_LEFT + 2 * ITEM_WIDTH + ITEM_SPACING - shuffle_count_text.get_width() - 5,
#                                      ITEM_TOP + ITEM_HEIGHT - shuffle_count_text.get_height() - 5))
#
#     # 游戏结束时显示结果和重玩按钮
#     if game_over:
#         # 绘制半透明遮罩
#         overlay = pygame.Surface((SCREEN_WIDTH, SCREEN_HEIGHT), pygame.SRCALPHA)
#         overlay.fill((0, 0, 0, 128))
#         screen.blit(overlay, (0, 0))
#
#         # 绘制游戏结果
#         result_font = pygame.font.SysFont(None, 50)  # 使用默认字体
#         result_text = result_font.render("恭喜你赢了!" if game_won else "游戏结束!",
#                                          True, WIN_COLOR if game_won else LOSE_COLOR)
#         screen.blit(result_text, (SCREEN_WIDTH // 2 - result_text.get_width() // 2, SCREEN_HEIGHT // 2 - 70))
#
#         # 绘制最终得分
#         final_score_font = pygame.font.SysFont(None, 36)  # 使用默认字体
#         final_score_text = final_score_font.render(f"最终得分: {score}", True, (255, 255, 255))
#         screen.blit(final_score_text, (SCREEN_WIDTH // 2 - final_score_text.get_width() // 2, SCREEN_HEIGHT // 2 - 20))
#
#         # 绘制总耗时
#         final_time_font = pygame.font.SysFont(None, 36)
#         final_time_text = final_time_font.render(f"总耗时: {minutes:02d}:{seconds:02d}", True, (255, 255, 255))
#         screen.blit(final_time_text, (SCREEN_WIDTH // 2 - final_time_text.get_width() // 2, SCREEN_HEIGHT // 2 + 30))
#
#         # 绘制重玩按钮
#         if restart_button_img:
#             if restart_button_hover:
#                 screen.blit(restart_button_hover_img, (
#                     RESTART_BUTTON_LEFT - (restart_button_hover_img.get_width() - RESTART_BUTTON_WIDTH) // 2,
#                     RESTART_BUTTON_TOP - (restart_button_hover_img.get_height() - RESTART_BUTTON_HEIGHT) // 2
#                 ))
#             else:
#                 screen.blit(restart_button_img, (RESTART_BUTTON_LEFT, RESTART_BUTTON_TOP))
#         else:
#             pygame.draw.rect(
#                 screen,
#                 BUTTON_HOVER_COLOR if restart_button_hover else BUTTON_COLOR,
#                 (RESTART_BUTTON_LEFT, RESTART_BUTTON_TOP, RESTART_BUTTON_WIDTH, RESTART_BUTTON_HEIGHT),
#                 border_radius=10
#             )
#             restart_text = pygame.font.SysFont(None, 36).render("再玩一次", True, BUTTON_TEXT_COLOR)  # 使用默认字体
#             screen.blit(
#                 restart_text,
#                 (
#                     RESTART_BUTTON_LEFT + (RESTART_BUTTON_WIDTH - restart_text.get_width()) // 2,
#                     RESTART_BUTTON_TOP + (RESTART_BUTTON_HEIGHT - restart_text.get_height()) // 2
#                 )
#             )
#
#         # 显示操作提示
#         hint_font = pygame.font.SysFont(None, 24)
#         hint_text = hint_font.render("按R键重新开始", True, (255, 255, 255))
#         screen.blit(hint_text, (SCREEN_WIDTH // 2 - hint_text.get_width() // 2, SCREEN_HEIGHT // 2 + 90))
#
#     pygame.display.flip()
#     clock.tick(90)
#
# pygame.quit()

import pygame
import random
import os
import math
from datetime import datetime  # 添加时间模块

# 初始化Pygame
pygame.init()

# 游戏窗口设置
SCREEN_WIDTH = 480
SCREEN_HEIGHT = 720
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption("羊了个羊")

# 颜色定义
BG_COLOR = (255, 255, 255)
TEXT_COLOR = (0, 0, 0)
CAPACITY_COLOR = (100, 100, 100)
ITEM_COLOR_1 = (0, 128, 0)  # 撤销道具颜色
ITEM_COLOR_2 = (0, 0, 128)  # 洗牌道具颜色
ITEM_TEXT_COLOR = (255, 255, 255)
WIN_COLOR = (0, 128, 0)  # 胜利文字颜色
LOSE_COLOR = (255, 0, 0)  # 失败文字颜色
BUTTON_COLOR = (65, 105, 225)  # 按钮背景色
BUTTON_HOVER_COLOR = (70, 130, 180)  # 按钮悬停色
BUTTON_TEXT_COLOR = (255, 255, 255)  # 按钮文字颜色
TIMER_COLOR = (255, 0, 0)  # 计时文字颜色

# 卡片尺寸和间距
CARD_WIDTH = 50
CARD_HEIGHT = 60
SPACING = 10
# 叠罗汉偏移量 - 减小偏移量使堆叠更紧凑
OVERLAP_OFFSET = 3

# 游戏区域布局
GRID_ROWS = 6
GRID_COLS = 6
grid_width = GRID_COLS * (CARD_WIDTH + SPACING) - SPACING
GRID_LEFT = (SCREEN_WIDTH - grid_width) // 2
GRID_TOP = 100

# 槽位区域设置
SLOT_ROWS = 1
SLOT_COLS = 7  # 最多存放7个卡片
slot_width = SLOT_COLS * (CARD_WIDTH + 5) - 5
SLOT_LEFT = (SCREEN_WIDTH - slot_width) // 2
SLOT_TOP = SCREEN_HEIGHT - CARD_HEIGHT - 50
SLOT_HEIGHT = CARD_HEIGHT + 20

# 道具按钮设置
ITEM_WIDTH = 60  # 道具按钮宽度
ITEM_HEIGHT = 60  # 道具按钮高度
ITEM_SPACING = 20  # 道具按钮间距
ITEM_TOP = 20  # 道具按钮顶部位置
ITEM_LEFT = (SCREEN_WIDTH - (2 * ITEM_WIDTH + ITEM_SPACING)) // 2  # 道具按钮左侧起始位置

# 重玩按钮设置
RESTART_BUTTON_WIDTH = 150
RESTART_BUTTON_HEIGHT = 50
RESTART_BUTTON_LEFT = (SCREEN_WIDTH - RESTART_BUTTON_WIDTH) // 2
RESTART_BUTTON_TOP = SCREEN_HEIGHT // 2 + 50

# 动画常量
ANIMATION_DURATION = 30  # 消去动画持续时间
MOVE_DURATION = 20  # 卡片移动动画持续时间

# 新增计时相关变量
start_time = None  # 开始时间
elapsed_time = 0  # 总耗时（秒）
is_paused = False  # 暂停状态

# 加载背景图像
try:
    image_folder = os.path.join(os.path.dirname(__file__), "image")
    background_path = os.path.join(image_folder, "back.png")
    background_img = pygame.image.load(background_path)
    background_img = pygame.transform.scale(background_img, (SCREEN_WIDTH * 2, SCREEN_HEIGHT))
    print("主背景图像加载成功")
    bg_x = 0
    BG_MOVE_SPEED = 1
except Exception as e:
    print(f"主背景图像加载失败: {e}")
    background_img = None
    bg_x = 0

# 加载槽位背景图像
try:
    slot_bg_path = os.path.join(image_folder, "back2.png")
    slot_bg_img = pygame.image.load(slot_bg_path)
    slot_bg_img = pygame.transform.scale(slot_bg_img, (slot_width + 20, SLOT_HEIGHT + 20))
    print("槽位背景图像加载成功")
except Exception as e:
    print(f"槽位背景图像加载失败: {e}")
    slot_bg_img = None

# 加载卡片图片
card_images = []
try:
    for i in range(7):
        if i == 0:
            tile_path = os.path.join(image_folder, "tile.png")
        else:
            tile_path = os.path.join(image_folder, f"tile{i}.png")

        if os.path.exists(tile_path):
            img = pygame.image.load(tile_path)
            img = pygame.transform.scale(img, (CARD_WIDTH, CARD_HEIGHT))
            card_images.append(img)
            print(f"卡片图片 {os.path.basename(tile_path)} 加载成功")
        else:
            print(f"卡片图片 {tile_path} 不存在")

    if not card_images:
        raise Exception("没有找到任何卡片图片")

except Exception as e:
    print(f"卡片图片加载失败: {e}")
    COLORS = [
        (255, 0, 0),  # 红
        (0, 255, 0),  # 绿
        (0, 0, 255),  # 蓝
        (255, 255, 0),  # 黄
        (128, 0, 128),  # 紫
        (255, 165, 0),  # 橙
        (0, 191, 255),  # 天蓝
    ]

# 加载道具按钮图片
try:
    # 撤销道具图片 (tuixiao.PNG)
    undo_img_path = os.path.join(image_folder, "chexiao.PNG")
    undo_button_img = pygame.image.load(undo_img_path)
    undo_button_img = pygame.transform.scale(undo_button_img, (ITEM_WIDTH, ITEM_HEIGHT))
    undo_button_hover_img = pygame.transform.scale(undo_button_img, (ITEM_WIDTH + 5, ITEM_HEIGHT + 5))
    print("撤销道具图片加载成功")
except Exception as e:
    print(f"撤销道具图片加载失败: {e}")
    undo_button_img = None
    undo_button_hover_img = None

try:
    # 洗牌道具图片 (xipai.PNG)
    shuffle_img_path = os.path.join(image_folder, "xipai.PNG")
    shuffle_button_img = pygame.image.load(shuffle_img_path)
    shuffle_button_img = pygame.transform.scale(shuffle_button_img, (ITEM_WIDTH, ITEM_HEIGHT))
    shuffle_button_hover_img = pygame.transform.scale(shuffle_button_img, (ITEM_WIDTH + 5, ITEM_HEIGHT + 5))
    print("洗牌道具图片加载成功")
except Exception as e:
    print(f"洗牌道具图片加载失败: {e}")
    shuffle_button_img = None
    shuffle_button_hover_img = None

# 加载重玩按钮图片
try:
    restart_img_path = os.path.join(image_folder, "chongwan.PNG")
    restart_button_img = pygame.image.load(restart_img_path)
    restart_button_img = pygame.transform.scale(restart_button_img, (RESTART_BUTTON_WIDTH, RESTART_BUTTON_HEIGHT))
    restart_button_hover_img = pygame.transform.scale(restart_button_img,
                                                      (RESTART_BUTTON_WIDTH + 5, RESTART_BUTTON_HEIGHT + 5))
    print("重玩按钮图片加载成功")
except Exception as e:
    print(f"重玩按钮图片加载失败: {e}")
    restart_button_img = None
    restart_button_hover_img = None


# 粒子效果类
class Particle:
    def __init__(self, x, y, color):
        self.x = x
        self.y = y
        self.color = color
        self.radius = random.randint(2, 5)
        self.speed_x = random.uniform(-3, 3)
        self.speed_y = random.uniform(-5, -1)
        self.gravity = 0.1
        self.life = random.randint(20, 40)

    def update(self):
        self.x += self.speed_x
        self.y += self.speed_y
        self.speed_y += self.gravity
        self.life -= 1

    def draw(self, surface):
        alpha = int((self.life / 40) * 255)
        if alpha > 0:
            s = pygame.Surface((self.radius * 2, self.radius * 2), pygame.SRCALPHA)
            pygame.draw.circle(s, (*self.color, alpha), (self.radius, self.radius), self.radius)
            surface.blit(s, (int(self.x - self.radius), int(self.y - self.radius)))


# 得分增加动画类
class ScorePopup:
    def __init__(self, x, y):
        self.x = x
        self.y = y
        self.value = "+1"
        self.font = pygame.font.SysFont(None, 30)  # 使用默认字体
        self.color = (255, 215, 0)  # 金色
        self.life = 40
        self.speed_y = -1

    def update(self):
        self.y += self.speed_y
        self.life -= 1

    def draw(self, surface):
        alpha = int((self.life / 40) * 255)
        if alpha > 0:
            text = self.font.render(self.value, True, self.color)
            text.set_alpha(alpha)
            surface.blit(text, (self.x, self.y))


# 初始化游戏函数
def init_game():
    global slots, score, game_over, game_won, grid, undo_history, remove_card_count, shuffle_count, particles, score_popups, eliminate_animation, eliminate_indices, animation_timer, card_moving, moving_card, start_x, start_y, target_x, target_y, move_timer
    global start_time, elapsed_time, is_paused  # 新增计时变量初始化

    slots = []
    score = 0
    game_over = False
    game_won = False
    remove_card_count = 3  # 撤销道具次数
    shuffle_count = 3  # 洗牌道具次数
    undo_history = []  # 撤销历史记录
    particles = []
    score_popups = []
    eliminate_animation = False
    eliminate_indices = []
    animation_timer = 0
    card_moving = False
    moving_card = None
    start_x = 0
    start_y = 0
    target_x = 0
    target_y = 0
    move_timer = 0

    # 初始化网格
    grid = []
    for row in range(GRID_ROWS):
        grid_row = []
        for col in range(GRID_COLS):
            # 为每个网格位置创建一个卡片堆
            # 增加卡片堆叠的层次 - 从0-3增加到0-6
            stack_size = random.randint(0, 6)
            stack = [random.randint(0, 6) for _ in range(stack_size)]
            grid_row.append(stack)
        grid.append(grid_row)

    # 确保游戏中有足够的卡片可玩
    # 增加总卡片数量
    while sum(len(stack) for row in grid for stack in row) < 50:
        row = random.randint(0, GRID_ROWS - 1)
        col = random.randint(0, GRID_COLS - 1)
        grid[row][col].append(random.randint(0, 6))

    # 计时初始化
    start_time = datetime.now()  # 开始新游戏时记录开始时间
    elapsed_time = 0
    is_paused = False


# 检查胜利条件
def check_victory(grid):
    # 检查网格中是否所有卡片都已被移除
    for row in grid:
        for stack in row:
            if len(stack) > 0:
                return False
    return True


# 撤销上次操作
def undo_last_move():
    global remove_card_count, slots, grid

    if remove_card_count <= 0:
        return  # 没有撤销次数了

    if not undo_history:
        return  # 没有历史记录可撤销

    # 获取最后一次操作
    row, col, card_type = undo_history.pop()

    # 将卡片放回网格
    grid[row][col].append(card_type)

    # 从槽位移除卡片
    if slots:
        slots.pop()

    # 减少撤销次数
    remove_card_count -= 1


# 洗牌函数
def shuffle_grid():
    global shuffle_count, grid

    if shuffle_count <= 0:
        return  # 没有洗牌次数了

    # 收集所有卡片
    all_cards = []
    for row in grid:
        for stack in row:
            all_cards.extend(stack)
            stack.clear()  # 清空所有堆

    # 洗牌
    random.shuffle(all_cards)

    # 重新分配卡片到网格
    index = 0
    for row in range(GRID_ROWS):
        for col in range(GRID_COLS):
            stack_size = min(random.randint(0, 6), len(all_cards) - index)  # 增加堆叠层次
            grid[row][col] = all_cards[index:index + stack_size]
            index += stack_size

    # 减少洗牌次数
    shuffle_count -= 1


# 初始化游戏
init_game()

# 游戏主循环
clock = pygame.time.Clock()
running = True

while running:
    # 事件处理新增计时控制
    mouse_pos = pygame.mouse.get_pos()
    restart_button_hover = (
            RESTART_BUTTON_LEFT <= mouse_pos[0] <= RESTART_BUTTON_LEFT + RESTART_BUTTON_WIDTH and
            RESTART_BUTTON_TOP <= mouse_pos[1] <= RESTART_BUTTON_TOP + RESTART_BUTTON_HEIGHT
    )

    # 道具按钮悬停检测
    undo_button_hover = (
            ITEM_LEFT <= mouse_pos[0] <= ITEM_LEFT + ITEM_WIDTH and
            ITEM_TOP <= mouse_pos[1] <= ITEM_TOP + ITEM_HEIGHT
    )

    shuffle_button_hover = (
            ITEM_LEFT + ITEM_WIDTH + ITEM_SPACING <= mouse_pos[0] <= ITEM_LEFT + 2 * ITEM_WIDTH + ITEM_SPACING and
            ITEM_TOP <= mouse_pos[1] <= ITEM_TOP + ITEM_HEIGHT
    )

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        elif event.type == pygame.MOUSEBUTTONDOWN:
            if game_over and restart_button_hover:
                init_game()
            elif not game_over:
                x, y = event.pos
                # 检查是否点击道具按钮
                if ITEM_LEFT <= x <= ITEM_LEFT + ITEM_WIDTH and ITEM_TOP <= y <= ITEM_TOP + ITEM_HEIGHT:
                    undo_last_move()
                elif ITEM_LEFT + ITEM_WIDTH + ITEM_SPACING <= x <= ITEM_LEFT + 2 * ITEM_WIDTH + ITEM_SPACING and ITEM_TOP <= y <= ITEM_TOP + ITEM_HEIGHT:
                    shuffle_grid()
                else:
                    # 计算点击位置
                    grid_col = (x - GRID_LEFT) // (CARD_WIDTH + SPACING)
                    grid_row = (y - GRID_TOP) // (CARD_HEIGHT + SPACING)
                    # 检查点击范围
                    if 0 <= grid_row < GRID_ROWS and 0 <= grid_col < GRID_COLS:
                        if len(grid[grid_row][grid_col]) > 0:
                            # 检查槽位是否已满
                            if len(slots) >= SLOT_COLS:
                                game_over = True
                                continue

                            # 记录操作历史用于撤销
                            card_type = grid[grid_row][grid_col][-1]
                            undo_history.append((grid_row, grid_col, card_type))

                            # 取出顶层卡片
                            moving_card = grid[grid_row][grid_col].pop()
                            start_x = GRID_LEFT + grid_col * (CARD_WIDTH + SPACING)
                            start_y = GRID_TOP + grid_row * (CARD_HEIGHT + SPACING) + (
                                len(grid[grid_row][grid_col])) * OVERLAP_OFFSET
                            target_x = SLOT_LEFT + len(slots) * (CARD_WIDTH + 5)
                            target_y = SLOT_TOP
                            card_moving = True
                            move_timer = 0

                            # 确保游戏开始后才计时
                            if not start_time:
                                start_time = datetime.now()

        # 新增：游戏暂停/继续控制（按P键）
        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_p and not game_over:
                is_paused = not is_paused
                if not is_paused and start_time:
                    # 恢复计时时调整开始时间
                    pause_duration = (datetime.now() - pause_start_time).total_seconds()
                    start_time = datetime.now() - datetime.timedelta(seconds=pause_duration)
            elif event.key == pygame.K_r and game_over:  # 新增按R键重新开始
                init_game()

    # 移动背景图
    bg_x -= BG_MOVE_SPEED
    if bg_x <= -SCREEN_WIDTH:
        bg_x = 0

    # 计算 elapsed_time（仅在游戏进行中更新）
    if start_time and not game_over and not is_paused:
        current_time = datetime.now()
        elapsed_time = (current_time - start_time).total_seconds()

    # 更新粒子效果
    for particle in particles[:]:
        particle.update()
        if particle.life <= 0:
            particles.remove(particle)

    # 更新得分动画
    for popup in score_popups[:]:
        popup.update()
        if popup.life <= 0:
            score_popups.remove(popup)

    # 绘制界面
    if background_img:
        screen.blit(background_img, (bg_x, 0))
        screen.blit(background_img, (bg_x + SCREEN_WIDTH, 0))
    else:
        screen.fill(BG_COLOR)

    # 绘制标题
    title_font = pygame.font.SysFont(None, 40)  # 使用默认字体
    title_text = title_font.render("羊了个羊", True, (0, 0, 0))
    screen.blit(title_text, (SCREEN_WIDTH // 2 - title_text.get_width() // 2, 50))

    # 绘制卡片堆，添加叠罗汉效果和鼠标悬停放大
    for row in range(GRID_ROWS):
        for col in range(GRID_COLS):
            x = GRID_LEFT + col * (CARD_WIDTH + SPACING)
            y = GRID_TOP + row * (CARD_HEIGHT + SPACING)
            stack = grid[row][col]
            for i, card_type in enumerate(stack):
                offset_y = i * OVERLAP_OFFSET
                card_x = x
                card_y = y + offset_y

                # 检查鼠标是否悬停在卡片上
                mouse_x, mouse_y = pygame.mouse.get_pos()
                if (
                        card_x <= mouse_x <= card_x + CARD_WIDTH
                        and card_y <= mouse_y <= card_y + CARD_HEIGHT
                ):
                    # 鼠标悬停，放大卡片
                    scale_factor = 1.2
                    scaled_width = int(CARD_WIDTH * scale_factor)
                    scaled_height = int(CARD_HEIGHT * scale_factor)
                    if card_images:
                        scaled_img = pygame.transform.scale(card_images[card_type], (scaled_width, scaled_height))
                        screen.blit(scaled_img, (
                            card_x - (scaled_width - CARD_WIDTH) // 2,
                            card_y - (scaled_height - CARD_HEIGHT) // 2
                        ))
                    else:
                        pygame.draw.rect(
                            screen,
                            COLORS[card_type],
                            (
                                card_x - (scaled_width - CARD_WIDTH) // 2,
                                card_y - (scaled_height - CARD_HEIGHT) // 2,
                                scaled_width,
                                scaled_height
                            )
                        )
                else:
                    if card_images:
                        screen.blit(card_images[card_type], (card_x, card_y))
                    else:
                        pygame.draw.rect(screen, COLORS[card_type], (card_x, card_y, CARD_WIDTH, CARD_HEIGHT))

    # 绘制槽位背景
    if slot_bg_img:
        screen.blit(slot_bg_img, (SLOT_LEFT - 10, SLOT_TOP - 10))
    else:
        pygame.draw.rect(
            screen,
            (200, 200, 200),
            (SLOT_LEFT - 5, SLOT_TOP - 5, slot_width + 10, SLOT_HEIGHT + 10),
            border_radius=10
        )

    # 绘制槽位标题
    slot_font = pygame.font.SysFont(None, 24)  # 使用默认字体
    slot_text = slot_font.render("卡槽", True, (0, 0, 0))
    screen.blit(slot_text, (SLOT_LEFT + slot_width // 2 - slot_text.get_width() // 2, SLOT_TOP - 30))

    # 绘制槽位中的卡片
    for i, card in enumerate(slots):
        if eliminate_animation and i in eliminate_indices:
            # 计算动画进度 (0到1之间)
            progress = animation_timer / ANIMATION_DURATION

            # 计算卡片位置和大小
            card_x = SLOT_LEFT + i * (CARD_WIDTH + 5)
            card_y = SLOT_TOP

            # 添加缩放效果
            scale = 1 - progress
            new_width = int(CARD_WIDTH * scale)
            new_height = int(CARD_HEIGHT * scale)

            # 居中显示缩放后的卡片
            draw_x = card_x + (CARD_WIDTH - new_width) // 2
            draw_y = card_y + (CARD_HEIGHT - new_height) // 2

            # 透明度调整
            alpha = int(255 * (1 - progress))

            if card_images:
                # 创建卡片的临时副本并设置透明度
                img = card_images[card].copy()
                img = pygame.transform.scale(img, (new_width, new_height))
                img.set_alpha(alpha)
                screen.blit(img, (draw_x, draw_y))
            else:
                surface = pygame.Surface((new_width, new_height), pygame.SRCALPHA)
                surface.fill((*COLORS[card], alpha))
                screen.blit(surface, (draw_x, draw_y))

            # 在动画结束前创建粒子效果
            if progress > 0.7:
                if random.random() < 0.3:
                    color = COLORS[card] if not card_images else (255, 255, 255)
                    for _ in range(3):
                        particles.append(Particle(
                            draw_x + new_width // 2,
                            draw_y + new_height // 2,
                            color
                        ))
        else:
            x = SLOT_LEFT + i * (CARD_WIDTH + 5)
            if card_images:
                screen.blit(card_images[card], (x, SLOT_TOP))
            else:
                pygame.draw.rect(screen, COLORS[card], (x, SLOT_TOP, CARD_WIDTH, CARD_HEIGHT))

    # 处理卡片移动动画
    if card_moving:
        progress = move_timer / MOVE_DURATION
        # 使用平滑的缓动函数替代线性插值
        ease_progress = 0.5 - 0.5 * math.cos(progress * math.pi)
        current_x = start_x + (target_x - start_x) * ease_progress
        current_y = start_y + (target_y - start_y) * ease_progress
        if card_images:
            screen.blit(card_images[moving_card], (current_x, current_y))
        else:
            pygame.draw.rect(screen, COLORS[moving_card], (current_x, current_y, CARD_WIDTH, CARD_HEIGHT))
        move_timer += 1
        if move_timer >= MOVE_DURATION:
            slots.append(moving_card)
            card_moving = False
            moving_card = None
            # 检查连续三个相同卡片
            if len(slots) >= 3 and slots[-1] == slots[-2] == slots[-3]:
                eliminate_animation = True
                eliminate_indices = [len(slots) - 3, len(slots) - 2, len(slots) - 1]
                animation_timer = 0
                score += 1
                # 创建得分动画
                score_popups.append(ScorePopup(
                    SLOT_LEFT + (len(slots) - 2) * (CARD_WIDTH + 5),
                    SLOT_TOP - 30
                ))

            # 再次检查槽位是否已满
            if len(slots) >= SLOT_COLS:
                game_over = True

            # 检查胜利条件
            if check_victory(grid):
                game_won = True
                game_over = True

    # 处理消去动画
    if eliminate_animation:
        animation_timer += 1
        if animation_timer >= ANIMATION_DURATION:
            # 从后向前删除，避免索引变化问题
            for i in sorted(eliminate_indices, reverse=True):
                del slots[i]
            eliminate_animation = False
            animation_timer = 0
            eliminate_indices = []

    # 绘制粒子效果
    for particle in particles:
        particle.draw(screen)

    # 绘制得分动画
    for popup in score_popups:
        popup.draw(screen)

    # 绘制状态信息
    status_font = pygame.font.SysFont(None, 28)  # 使用默认字体
    score_text = status_font.render(f"得分: {score}", True, TEXT_COLOR)
    screen.blit(score_text, (20, 20))

    # 绘制计时文本
    timer_font = pygame.font.SysFont(None, 36)
    minutes = int(elapsed_time // 60)
    seconds = int(elapsed_time % 60)
    timer_text = timer_font.render(f"时间: {minutes:02d}:{seconds:02d}", True, TIMER_COLOR)
    screen.blit(timer_text, (20, 60))  # 显示在得分下方

    # 绘制暂停提示（仅在暂停时显示）
    if is_paused and not game_over:
        pause_font = pygame.font.SysFont(None, 48)
        pause_text = pause_font.render("已暂停 (按P继续)", True, (255, 0, 0))
        screen.blit(pause_text, (SCREEN_WIDTH // 2 - pause_text.get_width() // 2, SCREEN_HEIGHT // 2 - 24))

    # 绘制槽位容量提示
    capacity_font = pygame.font.SysFont(None, 28)  # 使用默认字体
    capacity_text = capacity_font.render(f"已用: {len(slots)}/{SLOT_COLS}", True, CAPACITY_COLOR)
    screen.blit(capacity_text, (SCREEN_WIDTH - capacity_text.get_width() - 20, 20))

    # 绘制道具按钮
    # 撤销道具按钮
    if undo_button_img:
        if undo_button_hover:
            screen.blit(undo_button_hover_img, (
                ITEM_LEFT - (undo_button_hover_img.get_width() - ITEM_WIDTH) // 2,
                ITEM_TOP - (undo_button_hover_img.get_height() - ITEM_HEIGHT) // 2
            ))
        else:
            screen.blit(undo_button_img, (ITEM_LEFT, ITEM_TOP))
    else:
        pygame.draw.rect(
            screen,
            ITEM_COLOR_1 if not undo_button_hover else (0, 168, 0),
            (ITEM_LEFT, ITEM_TOP, ITEM_WIDTH, ITEM_HEIGHT),
            border_radius=5
        )
        # 绘制撤销图标
        undo_font = pygame.font.SysFont(None, 24)  # 使用默认字体
        undo_text = undo_font.render("撤销", True, ITEM_TEXT_COLOR)
        screen.blit(undo_text, (ITEM_LEFT + 10, ITEM_TOP + 18))

    # 洗牌道具按钮
    if shuffle_button_img:
        if shuffle_button_hover:
            screen.blit(shuffle_button_hover_img, (
                ITEM_LEFT + ITEM_WIDTH + ITEM_SPACING - (shuffle_button_hover_img.get_width() - ITEM_WIDTH) // 2,
                ITEM_TOP - (shuffle_button_hover_img.get_height() - ITEM_HEIGHT) // 2
            ))
        else:
            screen.blit(shuffle_button_img, (ITEM_LEFT + ITEM_WIDTH + ITEM_SPACING, ITEM_TOP))
    else:
        pygame.draw.rect(
            screen,
            ITEM_COLOR_2 if not shuffle_button_hover else (0, 0, 168),
            (ITEM_LEFT + ITEM_WIDTH + ITEM_SPACING, ITEM_TOP, ITEM_WIDTH, ITEM_HEIGHT),
            border_radius=5
        )
        # 绘制洗牌图标
        shuffle_font = pygame.font.SysFont(None, 24)  # 使用默认字体
        shuffle_text = shuffle_font.render("洗牌", True, ITEM_TEXT_COLOR)
        screen.blit(shuffle_text, (ITEM_LEFT + ITEM_WIDTH + ITEM_SPACING + 10, ITEM_TOP + 18))

    # 绘制道具剩余次数
    item_font = pygame.font.SysFont(None, 18)  # 使用默认字体
    undo_count_text = item_font.render(f"x{remove_card_count}", True, ITEM_TEXT_COLOR)
    shuffle_count_text = item_font.render(f"x{shuffle_count}", True, ITEM_TEXT_COLOR)
    screen.blit(undo_count_text, (ITEM_LEFT + ITEM_WIDTH - undo_count_text.get_width() - 5,
                                  ITEM_TOP + ITEM_HEIGHT - undo_count_text.get_height() - 5))
    screen.blit(shuffle_count_text, (ITEM_LEFT + 2 * ITEM_WIDTH + ITEM_SPACING - shuffle_count_text.get_width() - 5,
                                     ITEM_TOP + ITEM_HEIGHT - shuffle_count_text.get_height() - 5))

    # 游戏结束时显示结果和重玩按钮
    if game_over:
        # 绘制半透明遮罩
        overlay = pygame.Surface((SCREEN_WIDTH, SCREEN_HEIGHT), pygame.SRCALPHA)
        overlay.fill((0, 0, 0, 128))
        screen.blit(overlay, (0, 0))

        # 绘制游戏结果
        result_font = pygame.font.SysFont(None, 50)  # 使用默认字体
        result_text = result_font.render("恭喜你赢了!" if game_won else "游戏结束!",
                                         True, WIN_COLOR if game_won else LOSE_COLOR)
        screen.blit(result_text, (SCREEN_WIDTH // 2 - result_text.get_width() // 2, SCREEN_HEIGHT // 2 - 70))

        # 绘制最终得分
        final_score_font = pygame.font.SysFont(None, 36)  # 使用默认字体
        final_score_text = final_score_font.render(f"最终得分: {score}", True, (255, 255, 255))
        screen.blit(final_score_text, (SCREEN_WIDTH // 2 - final_score_text.get_width() // 2, SCREEN_HEIGHT // 2 - 20))

        # 绘制总耗时
        final_time_font = pygame.font.SysFont(None, 36)
        final_time_text = final_time_font.render(f"总耗时: {minutes:02d}:{seconds:02d}", True, (255, 255, 255))
        screen.blit(final_time_text, (SCREEN_WIDTH // 2 - final_time_text.get_width() // 2, SCREEN_HEIGHT // 2 + 30))

        # 绘制重玩按钮
        if restart_button_img:
            if restart_button_hover:
                screen.blit(restart_button_hover_img, (
                    RESTART_BUTTON_LEFT - (restart_button_hover_img.get_width() - RESTART_BUTTON_WIDTH) // 2,
                    RESTART_BUTTON_TOP - (restart_button_hover_img.get_height() - RESTART_BUTTON_HEIGHT) // 2
                ))
            else:
                screen.blit(restart_button_img, (RESTART_BUTTON_LEFT, RESTART_BUTTON_TOP))
        else:
            pygame.draw.rect(
                screen,
                BUTTON_HOVER_COLOR if restart_button_hover else BUTTON_COLOR,
                (RESTART_BUTTON_LEFT, RESTART_BUTTON_TOP, RESTART_BUTTON_WIDTH, RESTART_BUTTON_HEIGHT),
                border_radius=10
            )
            restart_text = pygame.font.SysFont(None, 36).render("再玩一次", True, BUTTON_TEXT_COLOR)  # 使用默认字体
            screen.blit(
                restart_text,
                (
                    RESTART_BUTTON_LEFT + (RESTART_BUTTON_WIDTH - restart_text.get_width()) // 2,
                    RESTART_BUTTON_TOP + (RESTART_BUTTON_HEIGHT - restart_text.get_height()) // 2
                )
            )

        # 显示操作提示
        hint_font = pygame.font.SysFont(None, 24)
        hint_text = hint_font.render("按R键重新开始", True, (255, 255, 255))
        screen.blit(hint_text, (SCREEN_WIDTH // 2 - hint_text.get_width() // 2, SCREEN_HEIGHT // 2 + 90))

    pygame.display.flip()
    clock.tick(90)

pygame.quit()